package Network.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class EchoClient {
    private Socket socket;

    public EchoClient(String serverIp,int serverPort) throws IOException {
        //在 new Socket对象的时候就涉及到”建立连接操作“
        //由于连接建立好了之后，服务器的信息就在操作系统中被TCP协议记录了，我们在应用程序层面就不需要保存IP和端口号了
        socket = new Socket(serverIp,serverPort); 
        //socket = new Socket();
        //socket.connect(serverIp,serverPort);

    }

    public void start() throws IOException {
        System.out.println("client start");

        Scanner scanner = new Scanner(System.in);

        try (InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
                Scanner scannerNet = new Scanner(inputStream);
                PrintWriter writer = new PrintWriter(outputStream);
                while(true) {
                    //1.从控制台读取用户的输入
                    System.out.print("> ");
                    String request = scanner.next();
                    //2.构造请求发送给服务器
                    writer.println(request);

                    //刷新缓冲区，保证数据发送出去
                    writer.flush();


                    //3.读取服务器的响应
                    if(!scannerNet.hasNextLine()) {
                        System.out.println("server close");
                        break;
                    }
                    String response = scannerNet.nextLine();
                    //4.把响应显示到控制台上
                    System.out.println(response);
                }
        } catch (IOException e) {
            e.printStackTrace(); 
        }
    }
    public static void main(String[] args) throws IOException {
        EchoClient echoClient = new EchoClient("127.0.0.1", 9090);
        echoClient.start();
    }
}
